<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<style>
  .vote-test {
    border: 2px solid #ddd;
    width: 80%;
    margin: 5px auto;
    padding: 20px;
    box-sizing: border-box;
  }
</style>

<body>
  <div id="app">
    总票数:{{total}}票
    <div>
      <vote-test v-for="person in personList" 
      v-bind="person"
      :total="total"
      @voting="person.vote=$event"
      ></vote-test>
    </div>
  </div>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.37/vue.global.js"></script>
  <script>
    var app = Vue.createApp({
      data: function () {
        return {
          personList: [
            { name: '周飘', vote: 0, sex:"m",age:"10" },
            { name: '志文', vote: 0, sex:"m",age:"10" },
            { name: '陈枫', vote: 0, sex:"m",age:"10" },
            { name: '吴超', vote: 0, sex:"m",age:"10" }
          ]
        }
      },
      computed: {
        //求vote总和
        total() {
          // pre:0 cur:0 
          return this.personList.reduce((pre, cur) => (pre += cur.vote, pre), 0);
          // ((a,b)=> ((a+=b.vote),a),0)



        }
      }
    });

    app.component('VoteTest', {
      template: `
        <div class="vote-test">
            <div>{{name}}  {{vote}}票</div>
            <div>{{Percent}}</div>
            <button @click="onClick">来一票</button>
          </div>
      `,
      props: ['name', 'vote','total'],
      methods: {
        onClick(){
          // this.vote = this.vote+1
          this.$emit('voting',this.vote+1);
        }
      },
      computed:{
        Percent(){
          if(this.total===0){
            return '0%';
          }
          return (this.vote/this.total*100).toFixed(2)+'%'
        }
      },
      inheritAttrs:false,
      emits:['voting']
    })

    app.mount("#app");
  </script>
</body>

</html>